import { _decorator, Component, Node, Button, Label, director, Vec3, UITransform, Rect, instantiate } from 'cc';
import { GameManager, GameEvent } from './GameManager';

const { ccclass, property } = _decorator;

@ccclass('CoinSpawner')
export class CoinSpawner extends Component {
    @property({ type: Node, tooltip: "硬币预制体" })
    coinPrefab!: Node;

    @property({ type: Button, tooltip: "生成硬币的按钮" })
    spawnButton!: Button;

    @property({ type: Node, tooltip: "硬币的父节点" })
    coinsParent!: Node;

    @property({ type: Node, tooltip: "硬币生成范围的参考节点（field）" })
    field!: Node;

    @property({ type: Number, tooltip: "每次生成新硬币后，所有硬币的缩小百分比（0.05=缩小5%）" })
    scaleDownPercent = 0.05;

    @property({ type: Number, tooltip: "硬币允许的最小缩放值（0.3=最小缩小到原来的30%）" })
    minScale = 0.3;

    // 生成成本（动态计算为当前硬币数量，不再通过编辑器配置）
    private spawnCost = 1;

    // 缓存属性
    private spawnRect!: Rect;
    private currentScore = 0;
    private gameManager!: GameManager;
    private spawnBtnLabel!: Label; // 按钮文本组件

    onLoad() {
        this.updateSpawnRect();
        this.initExistingCoinsScale();
        this.initGameManagerRef();
        this.initSpawnButtonLabel();
        this.updateSpawnCost(); // 初始化生成成本（基于当前硬币数量）
        this.updateSpawnButtonText(); // 初始设置按钮文本
        // 添加这行代码，初始化按钮状态
        this.updateButtonState(this.currentScore);
    }

    start() {
        if (this.spawnButton) {
            this.spawnButton.node.on(Button.EventType.CLICK, this.trySpawnNewCoin, this);
        } else {
            console.error("CoinSpawner: 未指定生成按钮！");
        }

        if (!this.coinsParent) {
            this.coinsParent = director.getScene().getChildByName("Canvas")!;
        }

        if (this.field) {
            this.field.on(Node.EventType.TRANSFORM_CHANGED, this.updateSpawnRect, this);
        } else {
            console.error("CoinSpawner: 请绑定field节点！");
        }

        // 绑定分数更新事件
        this.gameManager?.node.on(GameEvent.SCORE_UPDATED, this.onScoreUpdated, this);
        
        // 新增：监听硬币数量变化（添加/移除），动态更新成本
        this.coinsParent.on(Node.EventType.CHILD_ADDED, this.onCoinCountChanged, this);
        this.coinsParent.on(Node.EventType.CHILD_REMOVED, this.onCoinCountChanged, this);

        this.listenScoreUpdate(); // 分数不足时按钮置灰

    }

    // 初始化生成按钮的Label组件
    private initSpawnButtonLabel() {
        if (!this.spawnButton) {
            console.error("CoinSpawner: 未绑定生成按钮，无法设置文本！");
            return;
        }
        // 从按钮子节点"Label"获取文本组件（适配常见UI结构）
        this.spawnBtnLabel = this.spawnButton.node.getChildByName("Label")?.getComponent(Label);
        
        if (!this.spawnBtnLabel) {
            console.error("CoinSpawner: 按钮子节点\"Label\"未找到Label组件，请检查！");
        }
    }

    // 核心升级：计算当前生成成本（=当前有效硬币数量）
    private updateSpawnCost() {
        // 统计coinsParent下挂载CoinManager组件的有效硬币数量
        const validCoinCount = this.coinsParent.children.filter(
            child => child.getComponent("CoinManager") !== null
        ).length;
        
        // 首次生成时（硬币数量为0），成本默认为1
        this.spawnCost = validCoinCount > 0 ? validCoinCount : 1;
        console.log(`当前有效硬币数量：${validCoinCount}，生成成本更新为：${this.spawnCost}`);
    }

    // 更新按钮文本为"新硬币-X"（X为当前成本）
    private updateSpawnButtonText() {
        if (this.spawnBtnLabel) {
            this.spawnBtnLabel.string = `新硬币-${this.spawnCost}`;
        }
    }

    // 硬币数量变化时（添加/移除），同步更新成本和按钮文本
    private onCoinCountChanged() {
        this.updateSpawnCost();
        this.updateSpawnButtonText();
        // 添加这行代码，当成本变化时也更新按钮状态
        const gameManagerNode = director.getScene().getChildByName("Canvas").getChildByName("GameManager");
        this.gameManager = gameManagerNode?.getComponent(GameManager) || null;
        this.currentScore = this.gameManager.getCurrentScore();
        this.updateButtonState(this.currentScore);
    }

    // 初始化GameManager引用
    private initGameManagerRef() {
        const gameManagerNode = director.getScene().getChildByName("Canvas").getChildByName("GameManager");
        this.gameManager = gameManagerNode?.getComponent(GameManager) || null;
        if (this.gameManager) {
            this.currentScore = this.gameManager.getCurrentScore();
        } else {
            console.error("CoinSpawner: 未找到GameManager，无法实现扣分功能！");
        }
    }

    // 监听分数更新
    // 修改分数更新方法，添加按钮状态更新
    private onScoreUpdated(score: number, _targetScore: number) {
        this.currentScore = score;
        // 添加这行代码，当分数变化时更新按钮状态
        this.updateButtonState(score);
    }

    // 尝试生成硬币（先校验分数）
    private trySpawnNewCoin() {
        if (!this.gameManager) return;

        // 生成前同步最新分数和成本（双重保障）
        this.currentScore = this.gameManager.getCurrentScore();
        this.updateSpawnCost();

        // 分数不足时提示
        if (this.currentScore < this.spawnCost) {
            console.warn(`分数不足！生成需${this.spawnCost}分，当前${this.currentScore}分`);
            return;
        }

        // 扣分并生成硬币
        this.gameManager.deductScore(this.spawnCost);
        this.spawnNewCoin();
    }

    // 初始化已有硬币缩放
    private initExistingCoinsScale() {
        for (const coin of this.coinsParent.children) {
            if (coin.getComponent("CoinManager") && coin.scale.x === 1 && coin.scale.y === 1) {
                coin.setScale(1, 1, 1);
            }
        }
    }

    // 更新生成范围
    private updateSpawnRect() {
        if (!this.field) return;

        const fieldTransform = this.field.getComponent(UITransform);
        if (!fieldTransform) {
            console.error("CoinSpawner: field节点需要添加UITransform组件！");
            return;
        }

        const fieldPos = this.field.position;
        const fieldSize = fieldTransform.contentSize;
        const padding = 100;
        this.spawnRect = new Rect(
            fieldPos.x - fieldSize.width / 2,
            fieldPos.y - fieldSize.height / 1,
            fieldSize.width,
            fieldSize.height + padding * 4
        );
    }

    // 生成新硬币
    private spawnNewCoin() {
        if (!this.coinPrefab || !this.field) return;

        const coinSize = this.coinPrefab.getComponent(UITransform)?.contentSize || { width: 100, height: 100 };
        let newPosition: Vec3 | null = null;
        // 尝试20次寻找非重叠位置
        for (let i = 0; i < 20; i++) {
            const candidatePos = this.getRandomPosition();
            if (!this.isOverlapping(candidatePos, coinSize)) {
                newPosition = candidatePos;
                break;
            }
        }

        if (!newPosition) {
            console.warn("无法找到合适位置生成硬币，已返还分数");
            this.gameManager?.addScore(this.spawnCost); // 生成失败返还分数
            return;
        }

        // 实例化新硬币
        const newCoin = instantiate(this.coinPrefab);
        newCoin.setParent(this.coinsParent);
        newCoin.setPosition(newPosition);
        newCoin.name = `Coin_${Date.now()}`;
        const currentScale = this.coinsParent.children.length > 1 
            ? this.coinsParent.children[0].scale.x 
            : 1;
        newCoin.setScale(currentScale, currentScale, 1);

        // 缩小已有硬币
        this.scaleDownAllCoins(newCoin);
    }

    // 缩小所有已有硬币（排除新生成的）
    private scaleDownAllCoins(excludeCoin: Node) {
        for (const coin of this.coinsParent.children) {
            if (coin === excludeCoin || !coin.getComponent("CoinManager")) continue;

            const currentScale = coin.scale.x;
            const newScale = currentScale * (1 - this.scaleDownPercent);
            const finalScale = Math.max(newScale, this.minScale);
            coin.setScale(finalScale, finalScale, 1);
        }
    }

    // 生成随机位置
    private getRandomPosition(): Vec3 {
        const x = this.spawnRect.x + Math.random() * this.spawnRect.width;
        const y = this.spawnRect.y + Math.random() * this.spawnRect.height;
        return new Vec3(x, y, 0);
    }

    // 分数不足时按钮置灰（当前已存在的方法）
    private updateButtonState(currentScore: number) {
        if (this.spawnButton) {
            this.spawnButton.interactable = currentScore >= this.spawnCost;
        }
    }

    // 监听分数更新（按钮状态）
    private listenScoreUpdate() {
        if (this.gameManager?.scoreNode) {
            this.gameManager.scoreNode.on(GameEvent.SCORE_UPDATED, (currentScore: number) => {
                this.updateButtonState(currentScore);
            }, this);
        }
    }

    // 检测位置是否重叠
    private isOverlapping(position: Vec3, coinSize: { width: number, height: number }): boolean {
        const halfWidth = coinSize.width / 2;
        const halfHeight = coinSize.height / 2;

        for (const existingCoin of this.coinsParent.children) {
            if (!existingCoin.getComponent("CoinManager")) continue;

            const existingPos = existingCoin.position;
            const existingSize = existingCoin.getComponent(UITransform)?.contentSize || coinSize;
            const existingScale = existingCoin.scale.x;
            const existingHalfWidth = (existingSize.width / 2) * existingScale;
            const existingHalfHeight = (existingSize.height / 2) * existingScale;

            const xOverlap = Math.abs(position.x - existingPos.x) < (halfWidth + existingHalfWidth);
            const yOverlap = Math.abs(position.y - existingPos.y) < (halfHeight + existingHalfHeight);

            if (xOverlap && yOverlap) return true;
        }
        return false;
    }

    // 清理事件监听
    onDestroy() {
        if (this.spawnButton) {
            this.spawnButton.node.off(Button.EventType.CLICK, this.trySpawnNewCoin, this);
        }
        if (this.field) {
            this.field.off(Node.EventType.TRANSFORM_CHANGED, this.updateSpawnRect, this);
        }
        this.gameManager?.node.off(GameEvent.SCORE_UPDATED, this.onScoreUpdated, this);
        // 移除硬币数量变化监听
        this.coinsParent.off(Node.EventType.CHILD_ADDED, this.onCoinCountChanged, this);
        this.coinsParent.off(Node.EventType.CHILD_REMOVED, this.onCoinCountChanged, this);

        if (this.gameManager?.scoreNode) {
            this.gameManager.scoreNode.off(GameEvent.SCORE_UPDATED, this.updateButtonState, this);
        }
    }
}